#!/usr/bin/env groovy Jenkinsfile

// 定义环境变量属性-需要更改
def git_url="{{.AppInfo.GitlabUrl}}"
//def projectname="{{.AppConfig.AppsName}}"


// 定义环境变量属性-无需要更改
def credentialsId = "67bbe554-b961-48e9-bdbb-ea80dd8b41c0"
def ssh = "ssh -o StrictHostKeyChecking=no"
def scp = "scp -o StrictHostKeyChecking=no"
def deploy_user = "appuser"
def code_dir = "{{.AppConfig.DeployPath}}"
def test_ssh_command = 'echo check ssh connection' //定义 ssh remote 测试远程执行命令变量
def mkdir_codedir_cmd="mkdir -p ${code_dir}"
//def bak_code_cmd="mkdir -p ${code_dir}.bak && cp -rf ${code_dir} ${code_dir}.bak"
def reload_nginx_cmd="sudo {{.AppConfig.DeployRun}}"   // 命令
def static_target_files="{{.AppConfig.BuildPath}}/{{.AppConfig.PackageName}}"

node {
    try {
        stage('拉取代码') {
            git branch: "${BRANCH}", credentialsId: credentialsId, url: git_url
        }
        stage('编译代码') {
            sh "{{.AppConfig.BuildRun}}"
        }
        stage('上传ftp') {
            sh "tar czf dist.tar.gz {{.AppConfig.BuildPath}}"
            sh "goftp -h test-ftp-01 -p 21 -u deploy_user -p deploy_p@ssword -m upload -s dist.tar.gz -d {{.AppConfig.ProjectCode}}/{{.AppConfig.DeployEnv}}/{{.AppConfig.AppsName}}/${currentVersion}"

        }

    {{ range .CmdbVirtualList }}
        stage('部署代码-{{.Ipaddress}}') {
            //1. 测试remote host连通性
            sh "${ssh} ${deploy_user}@{{.Ipaddress}} ${test_ssh_command}"

            //2. 创建远程代码目录
            sh "${ssh} -tt ${deploy_user}@{{.Ipaddress}} ${mkdir_codedir_cmd}"
            //3. 备份前端 - 不需要
            //4. 拷贝前端代码到远程目录
            sh "${scp} -r ${static_target_files} ${deploy_user}@{{.Ipaddress}}:${code_dir}"
            //5. 执行命令
            sh "${ssh} -tt ${deploy_user}@{{.Ipaddress}} ${reload_nginx_cmd}"
        }
    {{end}}
    } catch (e) {
      		currentBuild.result = 'FAILURE'
      		throw e
    } finally {
        def currentResult = currentBuild.result ?: 'SUCCESS'
        if (currentResult == 'UNSTABLE') {
            echo 'This will run only if the run was marked as unstable'

        } else if (currentResult == 'FAILURE') {
            echo 'This will run only if the run was marked as FAILURE'
        } else {
            echo 'This will run only if the run was marked as SUCCESS'
        }
        sh "curl -m 10 --retry 3 -s 'http://luban.anji-plus.com/api/base/deploy/notify?job_name=${JOB_NAME}&build_number=${BUILD_NUMBER}&build_status=${currentResult}'"
    }
}